package cn.bnjy.util;

import cn.bnjy.entity.BaseMessage;
import cn.bnjy.entity.TextMessage;
import com.google.common.collect.Maps;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 描述：xml操作
 *
 * @date: 2018/11/4 1:26
 * @author: chavin
 */
@Slf4j
public class MessageFormatUtils {

    private MessageFormatUtils() {

    }

    /**
     * Xml转Map
     * @param request
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String, String> xml2Map(HttpServletRequest request) throws IOException{
        // 将解析的结果存入map集合中
        Map<String, String> map = Maps.newLinkedHashMap();
        InputStream inputStream = null;
        try {
            // 从request中获取流
            inputStream = request.getInputStream();
            // 使用dom4j读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 迭代
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            log.error("xml转map异常：" + e);
        } finally {
            if(inputStream != null) {
                inputStream.close();
            }
        }
        return map;
    }

    /**
     * 对象转Xml
     * @param baseMessage
     * @return
     */
    public static String obj2Xml(Object obj) {
        XStream xs = new XStream();
        xs.alias("xml", obj.getClass());
        return xs.toXML(obj);
    }

    public static void main(String[] args) {
        TextMessage textMessage = new TextMessage();
        textMessage.setContent("123");

        BaseMessage message = new TextMessage("abc");
        ((TextMessage) message).setContent("bdddd");
        System.out.println(obj2Xml(message));

    }
}
